import Vuex from '@/store/index.js'

// const baseUrl = 'http://yapi.smart-xwork.cn/mock/101230'
// const baseUrl = 'http://jkwxtest.xyz:21790/mjServer'
export const baseUrl = '/mjServer'
// export const baseUrl = 'https://cpwjw-fxrqgl.bjchp.gov.cn:54557/mjServer'

export function get(url, data, config = {}, isAll = false) {
  url = (url.startsWith('http') || url.startsWith('//')) ? url : baseUrl + url
  return new Promise((resolve, reject) => {
    uni.request({
      method: 'GET',
      url,
      data,
      header: {
        'token': Vuex.state.token,
        ...config
      },
      success(res = {}) {
        let { data = "{}" } = res

        try {
          data = typeof data === 'string' ? JSON.parse(data) : data

          if (data.errNo) {
            data.errNo = +data.errNo
          }
        } catch (error) {
          data = {}
        }

        if (isAll) {
          return resolve(data)
        }

        if (data && (data.errNo === 0 || data.errcode === 0)) {
          resolve(data.data)
        } else {
          // 判断是否登录超时
          if (data.errNo === 100) {
            uni.showToast({
              title: '请求失败：' + (data.errMsg || data.errmsg),
              icon: 'none'
            })

            Vuex.commit('logout')
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/index',
              });
            }, 0);

            return
          }

          uni.showToast({
            title: '请求失败：' + (data.errMsg || data.errmsg),
            icon: 'none'
          })
          resolve()
        }
      },
      fail(err) {
        if (isAll) {
          return resolve(err)
        }

        uni.showToast({
          title: '请求错误',
          icon: 'none'
        })
        resolve()
      }
    })
  })
}

export function post(url, data = {}, config = {}) {
  const { isAll = false, needLogin = true, showToast = true, ...options } = config
  url = (url.startsWith('http') || url.startsWith('//')) ? url : baseUrl + url
  return new Promise((resolve, reject) => {
    uni.request({
      method: 'POST',
      url,
      data: JSON.stringify(data),
      header: {
        'token': Vuex.state.token,
        "content-type": "text/plain; charset=utf-8",
        ...options
      },
      success(res = {}) {
        let { data = "{}" } = res
        console.log('resssss', res, data);
        try {
          data = typeof data === 'string' ? JSON.parse(data) : data

          if (data.errNo) {
            data.errNo = +data.errNo
          }
        } catch (error) {
          data = {}
        }

        console.log('post-data', data);

        if (isAll) {
          return resolve(data)
        }
        if (data && (data.errNo === 0 || data.errcode === 0)) {
          resolve(data.data || true)
        } else {
          console.log('needLogin', needLogin);
          // 判断是否登录超时
          if (data.errNo === 100 && needLogin) {
            Vuex.commit('logout')
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/index',
              });
            }, 0);

            return
          }

          showToast && uni.showToast({
            title: (data.errMsg || data.errmsg),
            icon: 'none'
          })
          resolve()
        }
      },
      fail(err) {
        if (isAll) {
          return resolve(err)
        }
        uni.showToast({
          title: '请求错误',
          icon: 'none'
        })
        resolve()
      }
    })
  })
}

export function request(options = {}) {
  const { header = {} } = options

  return uni.request({
    ...options,
    header: {
      ...header,
      'token': Vuex.state.token,
    }
  })
}

const Http = {
  get,
  post,
  request
}

export function httpMixin() {
  return {
    data() {
      return {
        $http: Http
      }
    },
    created() {
      this.$http = Http
      console.log('created', this.$http);
    }
  }
}

export default Http